using System;
using System.Drawing;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace Glpt.Common
{
    /// <summary>
    /// 屏幕信息类
    /// </summary>
    public class ScreenInfo
    {
        [DllImportAttribute("gdi32.dll")]
        private static extern bool BitBlt(
        IntPtr hdcDest,    //目标设备的句柄 
        int nXDest,        // 目标对象的左上角的X坐标 
        int nYDest,        // 目标对象的左上角的X坐标 
        int nWidth,        // 目标对象的矩形的宽度 
        int nHeight,       // 目标对象的矩形的长度 
        IntPtr hdcSrc,     // 源设备的句柄 
        int nXSrc,         // 源对象的左上角的X坐标 
        int nYSrc,         // 源对象的左上角的X坐标 
        System.Int32 dwRop // 光栅的操作值 
        );

        /// <summary>
        /// 获取屏幕图像
        /// </summary>
        /// <returns>图像</returns>
        public static Bitmap GetFullScreenImage()
        {
            //建立屏幕Graphics
            Graphics grpScreen = Graphics.FromHwnd(IntPtr.Zero);
            //根据屏幕大小建立位图
            Bitmap bitmap = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, grpScreen);
            //建立位图相关Graphics
            Graphics grpBitmap = Graphics.FromImage(bitmap);
            //建立屏幕上下文
            IntPtr hdcScreen = grpScreen.GetHdc();
            //建立位图上下文
            IntPtr hdcBitmap = grpBitmap.GetHdc();
            //将屏幕捕获保存在图位中
            BitBlt(hdcBitmap, 0, 0, bitmap.Width, bitmap.Height, hdcScreen, 0, 0, 0x00CC0020);
            //关闭位图句柄
            grpBitmap.ReleaseHdc(hdcBitmap);
            //关闭屏幕句柄
            grpScreen.ReleaseHdc(hdcScreen);
            //释放位图对像
            grpBitmap.Dispose();
            //释放屏幕对像
            grpScreen.Dispose();
            //返回捕获位图
            return bitmap;
        }

        /// <summary>
        /// 获取屏幕图像的字节流
        /// </summary>
        /// <returns>字节流</returns>
        public static byte[] GetFullScreen()
        {
            MemoryStream ms = new MemoryStream();
            Bitmap bit = GetFullScreenImage();
            bit.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            bit.Dispose();
            ms.Position = 0;
            byte[] buf = ms.ToArray();
            ms.Close();
            return buf;
        }
    }
}
